/**
 * Created by Administrator on 2017/3/4.
 */
var express = require('express');

var router = express.Router();

var moment = require('moment');

var CheckLogin = require('../module/checkLogin');

var upload = require('../module/multer');

var module_collection = require('../module/database');

var thumbnail = require('../module/gm');

var User = module_collection.User;

var Theme = module_collection.Theme;

var Comment = module_collection.Comment;

var Subscribe = module_collection.Subscribe;

var MyComment = module_collection.MyComment;

var MyTheme = module_collection.MyTheme;

var History = module_collection.History;


router.post('/posting', CheckLogin, function (req, res) {
    console.log(req.body.message);
    var user_id = req.cookies.wcID;
    var forun_id = req.query.forumId;
    var the_id;
    // photoUpload(req.file);
    Theme.find(function (err, data) {
        console.log(data.length);
        if (!err) {
            if (data.length == 0) {
                the_id = 1;
            } else {
                the_id = data[0].id + 1;
            }
            var img_url = "";
            var out_img = "";
            // if (req.file) {
            //     img_url = '/uploads/' + req.file.filename;
            //     out_img = '/uploads-min/' + req.file.filename;
            // } else {
            //     img_url = '';
            //     out_img = '';
            // }
            User.find({
                id: user_id
            }, function (err, data) {
                var user_data = data[0]._id;
                var time = moment().utcOffset(-8).format('YYYY-MM-DD HH:mm:ss');
                console.log(time);
                // Comment.find(function (err, data) {
                //     if (data.length == 0) {
                //         com_id = 1;
                //     } else {
                //         com_id = data[0].id + 1;
                //     }
                //     var comment = new Comment({id: com_id,content: req.body.content,theme_id: the_id,time: time,
                //         img_url: img_url,out_img: out_img,comer_id: '',user_id: user_id,permission:1
                //     });
                    var theme = new Theme({
                        id: the_id,content: req.body.message,user_id: user_id,time:time,update_time: time,
                        img_url: img_url,out_img: out_img,user_info: user_data,forum_id: forun_id,content_num: 0,like_num: 0,permission:1
                    });
                    theme.save(function (err, data) {


                        
                        if (err) {
                            console.log('主题数据存储失败' + err);
                        } else {
                            console.log('主题数据存储成功');
                            var mytheme = new MyTheme({
                                user_id: user_id,
                                theme_id: the_id,
                                theme_info: data._id
                            });
                            mytheme.save(function(err,data){
                                if(!err){
                                    res.status(200).json({
                                        code: 1,
                                        message: "发帖成功"
                                    });
                                }
                            });
                            // comment.save(function (err) {
                            //     if (err) {
                            //         console.log('留言数据存储失败' + err);
                            //     } else {
                            //         console.log('留言数据存储成功');
                            //     }
                                
                            // })
                        }
                    });

                // }).sort({
                //     id: -1
                // }).limit(1);
            })

        } else {
            // the_id = 0;
        }
    }).sort({
        id: -1
    }).limit(1).populate('user_info');

});

router.post('/reply', CheckLogin, function (req, res) {
    var theme_id = req.query.theme_id;
    var user_id = req.cookies.wcID;
    var comer_id = '';
    var com_id;
    console.log(req.body);
    console.log(req.query.comer_id + 'req_comer');
    if (req.query.comer_id != null) {
        comer_id = req.query.comer_id;
        console.log(comer_id + 'comer1');

    }

    Comment.find(function (err, data) {
        console.log('aaaaa');
        if (!err) {
            if (data.length == 0) {
                com_id = 1;

            } else {
                com_id = data[0].id + 1;
            }
            var img_url = "";
            var out_img = "";
            // if (req.file) {
            //     img_url = '/uploads/' + req.file.filename;
            //     out_img = '/uploads-min/' + req.file.filename;
            // } else {
            //     img_url = '';
            //     out_img = '';
            // }
            var time = moment().utcOffset(-8).format('YYYY-MM-DD HH:mm:ss');
            console.log(time);
            console.log(comer_id + 'comer2');
            var comment = new Comment({
                id: com_id,content: req.body.message,time: time,theme_id: theme_id,img_url: img_url,
                out_img: out_img,comer_id: comer_id,user_id: user_id,update: false,permission:1
            });
            comment.save(function (err, data) {
                if (err) {
                    console.log('留言' + err.message);
                } else {
                    var mycomment = new MyComment({
                        user_id: user_id,comment_id: com_id,comment_info: data._id,update: false
                    });
                    mycomment.save();
                    Theme.update({
                        id: theme_id
                    }, {
                        update_time: time
                    }, function (err, data) {
                        console.log('留言数据存储成功');
                    });
                    console.log(theme_id); 
                    Subscribe.find({
                        theme_id: theme_id
                    },function (err,data) {
                    	if(!err){
                    		console.log(data);
                            for (var i = 0; i < data.length; i++) {
                                var element = data[i].user_id;
                                Subscribe.update({user_id:element},{update:true},function(err,data){
                                    console.log(data);
                                })
                                
                            }
                        	console.log('订阅已更新');
                    	}else{
                    		console.log(err.message);
                    	}
                    	
                    })
                    if (req.query.comer_id != null) {
                        MyComment.update({
                            comment_id: comer_id
                        }, {
                            update: true
                        }, function () {
                            console.log(comer_id + '有新的留言');
                        })
                    }

                    Comment.count({
                        theme_id: theme_id
                    }, function (err, data) {
                        if (!err) {
                            var count = data;
                            console.log(count);
                            Theme.update({
                                id: theme_id
                            }, {
                                content_num: count
                            }, function (err, data) {
                                if (!err) {
                                    console.log('留言数更新成功');
                                    res.status(200).json({
                                        code: 1,
                                        message: "留言成功"
                                    });
                                } else {
                                    console.log('留言数更新失败');
                                }
                            })
                        }
                    })

                }

            });
        }
    }).sort({
        id: -1
    }).limit(1).populate('comment_info');
});

router.post('/upload', upload.single('uPhoto'),function(req,res){ 
    var theme_id = req.query.theme_id;
    console.log(theme_id);
    if(theme_id == "false"){
        var tableName = "Theme";
    }else{
        var tableName = "Comment";
    }
    console.log(req.file); 
    photoUpload(req.file);
    var img_url;
    var out_img;
    if (req.file) {
    	
        img_url = '/uploads/' + req.file.filename;
        out_img = '/uploads-min/' + req.file.filename;
        if (req.file.mimetype == 'image/gif') {
        	var fileformat = (req.file.filename).split('.');
            out_img = '/uploads-min/' + fileformat[0] + '.png';
        }
    } else {
        img_url = '';
        out_img = '';
    }
    console.log(tableName);
    setTimeout(function() {
      if(tableName == "Theme"){
            Theme.findOne(function(err,data){
                if(!err){
                    Theme.update({id:data.id},{img_url:img_url,out_img:out_img},function(err,data){
                        if(!err){
                            console.log(data);  
                        }else{
                            console.log(err.message)
                        }
                        res.send();
                    })
                }else{
                    console.log(err.message)
                }
                
            }).sort({id:-1})
      }else if(tableName == "Comment"){
            Comment.findOne(function(err,data){
                if(!err){
                    Comment.update({id:data.id},{img_url:img_url,out_img:out_img},function(err,data){
                        if(!err){
                            console.log(data);  
                        }else{
                            console.log(err.message)
                        }
                        res.send();
                    })
                }else{
                    console.log(err.message)
                }
                
            }).sort({id:-1})
      }
        
    }, 500);
    




})

router.post('/keywords', function (req, res) {
    var parent = /^\d*$/;
    var keyword = req.body.val;
    if (parent.test(req.body.val)) {
        keyword = parseInt(req.body.val);
        console.log("aaa");
    }
    // console.log(typeof keyword);
    var re = new RegExp("^[A-Za-z0-9\u4e00-\u9fa5]*" + keyword + "[A-Za-z0-9\u4e00-\u9fa5]*$");
    var find_obj = {
        content: re
    };
    if (parent.test(keyword)) {
        console.log("bbb");
        find_obj = {
            id: keyword
        }
    }
    console.log(find_obj);

    Theme.find(find_obj, function (err, data) {
        if (!err) {
            if (data.length != 0) {
                console.log(data);
                res.status(200).json({
                    code: 0,
                    message: "查找到主題",
                    recommend: data
                });
            } else {
                res.status(200).json({
                    code: 1,
                    message: "未找到"
                });
            }
        } else {
            res.status(200).json({
                code: 1,
                message: err.message
            });
        }

    }).populate("user_info");
});

router.post('/hotTheme', function (req, res) {
    var hot = [{
        content: "我的世界"
    }, {
        content: "英雄联盟"
    }, {
        content: "炉石传说"
    }]

    res.status(200).json({
        recommend: hot
    });
})

router.post('/delete', function (req, res) {
    var id = req.body.id;
    var user_id = req.cookies.wcID;
    var tableName = req.body.tableName;
    console.log(tableName);
    console.log(id);
    if (tableName == 'History') {
        History.remove({
            theme_id: id,
            user_id: user_id
        }, function (err, data) {
            if (!err) {
                res.status(200).json({
                    code: 1,
                    message: '删除成功'
                });
            } else {
                res.status(200).json({
                    code: 0,
                    message: '因为未知的错误，删除失败'
                });
            }
        })
    } else if (tableName == 'Comment') {
        Comment.update({
            id: id,
        },{permission:0}, function (err, data) {
            if (!err) {
                console.log(data);
                res.send();
                MyComment.remove({
                    comment_id: id
                }, function (err, data) {
                    if (!err) {
                        res.status(200).json({
                            code: 1,
                            message: '删除成功'
                        });
                    } else {
                        res.status(200).json({
                            code: 0,
                            message: '因为未知的错误，删除失败'
                        });
                    }
                })
            } else {
                res.status(200).json({
                    code: 0,
                    message: '因为未知的错误，删除失败'
                });
            }
        })

    } else if (tableName == 'Theme') {
        Theme.update({
            id: id,
        },{permission:0}, function (err, data) {
            if (!err) {
                console.log(data);
                MyTheme.remove({
                    theme_id: id
                }, function (err, data) {
                    if (!err) {
                        res.status(200).json({
                            code: 1,
                            message: '删除成功'
                        });
                    } else {
                        res.status(200).json({
                            code: 0,
                            message: '因为未知的错误，删除失败'
                        });
                    }
                })
            } else {
                res.status(200).json({
                    code: 0,
                    message: '因为未知的错误，删除失败'
                });
            }
        })
    } else if (tableName == 'Subscribe') {
        Subscribe.remove({
            theme_id: id,
            user_id: user_id
        }, function (err, data) {
            if (!err) {
                res.status(200).json({
                    code: 1,
                    message: '删除成功'
                });
            } else {
                res.status(200).json({
                    code: 0,
                    message: '因为未知的错误，删除失败'
                });
            }
        });

    };

});

router.post('/like',function(req,res){
    var likebool = req.body.likebool;
    // console.log(typeof likebool);
    var theme_id = req.body.sectionId;
    var favaCount = req.body.favaCount;
    console.log(favaCount);
    if(likebool == "true"){
        Theme.update({id:theme_id},{like_num:favaCount},function (err,data) {
            
        })    
                 
    }else{
      Theme.update({id:theme_id},{like_num:favaCount},function (err,data) {
            
        })    
    }
    res.status(200).json({code:1});  
})

function photoUpload(file) {
    if (file != undefined) {
        var file = file;
        if (file.mimetype == 'image/jpeg') {
            console.log('格式为jpg');
        }
        var fileformat = (file.filename).split('.');
        var fileName = fileformat[0];
        var fileType = fileformat[fileformat.length - 1];
        var img_url = 'public/uploads/' + file.filename;
        var out_img = 'public/uploads-min/' + file.filename;
        thumbnail(img_url, out_img, fileType, fileName);
    }
}

module.exports = router;